package com.csnf.controller;


import com.csnf.config.MinioConfig;
import csnf.com.entity.*;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UploadController {
    private final MinioConfig minioConfig;

    public UploadController(MinioConfig minioConfig) {
        this.minioConfig = minioConfig;
    }

    @RequestMapping("/uploadUserTouxiang")
    public ResponseObject uploadUserTouxiang(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return ResponseObject.error("上传失败", 400);
        } else {
            try {
                String uuid = UUID.randomUUID().toString();
                String originalFilename = uuid+".jpg";


                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(file.getBytes());


                minioConfig.minioClient().putObject(
                        PutObjectArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .object(originalFilename)
                                .stream(byteArrayInputStream, file.getSize(), -1)
                                .contentType(file.getContentType())
                                .build()
                );
                return ResponseObject.success(originalFilename, 200);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ServerException e) {
                throw new RuntimeException(e);
            } catch (InsufficientDataException e) {
                throw new RuntimeException(e);
            } catch (ErrorResponseException e) {
                throw new RuntimeException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            } catch (InvalidKeyException e) {
                throw new RuntimeException(e);
            } catch (InvalidResponseException e) {
                throw new RuntimeException(e);
            } catch (XmlParserException e) {
                throw new RuntimeException(e);
            } catch (InternalException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
